import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { Bar } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
import { FaFileAlt, FaBell } from 'react-icons/fa';
import './Dashboard.css';

// 注册Chart.js组件
Chart.register(...registerables);

const PaymentManagerDashboard = () => {
  const [stats, setStats] = useState({
    totalEmployees: 0,
    sentNotifications: 0,
    unreadSentNotifications: 0,
    notificationsByMonth: { labels: [], data: [] }
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 获取仪表盘统计数据
  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        setLoading(true);

        // 获取员工总数
        const employeesRes = await axios.get('/users/employees');
        const totalEmployees = employeesRes.data.length;

        // 获取已发送通知统计
        const sentStatsRes = await axios.get('/notifications/sent/stats');
        const { totalSent, unreadSent } = sentStatsRes.data;

        // 获取月度通知统计
        const monthlyData = await getMonthlyNotificationStats();

        setStats({
          totalEmployees,
          sentNotifications: totalSent,
          unreadSentNotifications: unreadSent,
          notificationsByMonth: monthlyData
        });
      } catch (err) {
        console.error('获取仪表盘数据失败', err);
        setError('获取数据失败，请刷新页面重试');
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  // 获取月度通知统计数据
  const getMonthlyNotificationStats = async () => {
    try {
      // 获取当前用户信息
      const currentUser = JSON.parse(localStorage.getItem('currentUser'));
      if (!currentUser) {
        throw new Error('用户未登录');
      }

      // 获取当前用户发送的所有通知
      const res = await axios.get('/notifications');
      const allNotifications = res.data.notifications || [];
      const sentNotifications = allNotifications.filter(notification => 
        notification.sender_id === currentUser.id
      );

      // 按月份统计通知数量
      const monthlyData = {};
      sentNotifications.forEach(notification => {
        const date = new Date(notification.created_at);
        const month = date.getMonth(); // 0-11
        const year = date.getFullYear();
        const key = `${year}-${month}`;
        monthlyData[key] = (monthlyData[key] || 0) + 1;
      });

      // 排序并格式化月份标签
      const sortedMonths = Object.keys(monthlyData).sort();
      const labels = sortedMonths.map(key => {
        const [year, month] = key.split('-');
        return `${parseInt(month) + 1}月`; // 转换为1-12月
      });
      const data = sortedMonths.map(key => monthlyData[key]);

      return { labels, data };
    } catch (err) {
      console.error('获取月度统计失败', err);
      return { labels: [], data: [] };
    }
  };

  // 月度通知图表数据
  const monthlyChartData = {
    labels: stats.notificationsByMonth.labels,
    datasets: [
      {
        label: '创建任务数',
        data: stats.notificationsByMonth.data,
        backgroundColor: 'rgba(54, 162, 235, 0.5)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 1
      }
    ]
  };

  if (loading) {
    return <div className="dashboard-loading">加载中...</div>;
  }

  if (error) {
    return <div className="dashboard-error">{error}</div>;
  }

  return (
    <div className="dashboard-container">
      <h1 className="dashboard-title">团队主管工作台</h1>

      {/* 快速操作 */}
      <div className="quick-actions">
        <Link to="/notifications/create" className="btn btn-primary btn-large">
          <FaFileAlt className="btn-icon"/>
          <span>创建新任务</span>
        </Link>

        <Link to="/notifications" className="btn btn-secondary btn-large">
          <FaBell className="btn-icon" />
          <span>查看已建任务</span>
        </Link>
      </div>

      {/* 统计卡片 */}
      <div className="stats-cards">
        <div className="stat-card">
          <div className="stat-card-content">
            <h3 className="stat-card-title">员工总数</h3>
            <p className="stat-card-value">{stats.totalEmployees}</p>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-card-content">
            <h3 className="stat-card-title">已创建任务</h3>
            <p className="stat-card-value">{stats.sentNotifications}</p>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-card-content">
            <h3 className="stat-card-title">未查收任务</h3>
            <p className="stat-card-value">{stats.unreadSentNotifications}</p>
          </div>
        </div>
      </div>

      {/* 图表区域 */}
      <div className="charts-container">
        <div className="chart-card">
          <h3 className="chart-title">月度创建任务统计</h3>
          <div className="chart-content">
            <Bar
              data={monthlyChartData}
              options={{
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                  y: {
                    beginAtZero: true,
                    title: { display: true, text: '任务数量' },
                    ticks: {
                      precision: 0,
                      stepSize: 1
                    }
                  }
                }
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default PaymentManagerDashboard;